package com.zen.demo.sys.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author alexzshl
 * @since 2022/1/28 22:23
 */
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CHAR})
@MappedTypes({List.class})
public class DelimiterStringTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, List<String> strings, JdbcType jdbcType) throws SQLException {
        String value = StringUtils.arrayToDelimitedString(strings.toArray(), ",");
        ps.setString(index, value);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String value = resultSet.getString(s);
        String[] strings = StringUtils.delimitedListToStringArray(value, ",");
        return Arrays.asList(strings);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);
        String[] strings = StringUtils.delimitedListToStringArray(value, ",");
        return Arrays.asList(strings);
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);
        String[] strings = StringUtils.delimitedListToStringArray(value, ",");
        return Arrays.asList(strings);
    }
}
